package cn.itcast.crawler;

import com.sun.javafx.fxml.builder.URLBuilder;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.net.URISyntaxException;

// 带参数的HttpGet请求实现  查询网页中http://www.itcast.cn中所有关于java的学习视频
// 在浏览器中查看地址为http://www.itcast.cn?keys=java  带有一个参数keys = java
// 主要是通过UrlBuilder对象设置参数，通过set方法实现多个参数的设置
@SuppressWarnings("all")
public class HttpGetParmTest {
    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String uri = "http://www.itcast.cn";
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(uri);
            // 设置地址相关参数可以设置多个，只需要在后面实现.setParameter方法即可
            uriBuilder.setParameter("keys","java");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        CloseableHttpResponse response = null;
        try {
            // 创建get
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            response = httpClient.execute(httpGet);
            // 判断
            if (response.getStatusLine().getStatusCode() == 200) {
                // 状态码为200，表明此时相应成功
                // 获取内容，设置内容的编码
                String content = EntityUtils.toString(response.getEntity(),"utf8");
                System.out.println(content);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
